<!-- 叶子节内容 -->
<template>
  <div v-loading="loading" class="switchTableTabs">
    <div class="content-wrap">
      <px-row :gutter="16">
        <px-col :span="24">
          <div class="black">
            <modelTitle :title="currentSystem + '能源趋势'" />
            <btnImageAndData
              v-has="'ALL_ENERGY_CONSUME_MEASUREMENT_DOWNLOAD'"
              class="download"
              @exportChange="val => handlerExport(val, 'line', 'trendChartRef')"
            />
            <div v-if="resData?.summaryTrend?.yaxis?.length" ref="trendChartRef" class="chart-wrap" />
            <px-empty v-else :image-size="50" />
            <div v-show="resData?.summaryTrend?.yaxis?.length" class="switch-wrap" @click="handleSwitch">
              <px-icon><Switch size="small" /></px-icon><span class="text">{{ switchText }}</span>
            </div>
          </div>
        </px-col>
      </px-row>
      <px-row :gutter="16" class="mg-top-16">
        <px-col :span="24">
          <div class="black">
            <modelTitle :title="currentSystem + '消耗能源'" />
            <btnImageAndData
              v-has="'ALL_ENERGY_CONSUME_MEASUREMENT_DOWNLOAD'"
              class="download"
              :exportImage="Boolean(false)"
              @exportChange="val => handlerExport(val, 'table', '')"
            />
            <px-table v-if="tableData?.length" class="table-wrap" height="249px" :data="tableData" size="small" border stripe show-overflow-tooltip>
              <px-table-column type="index" label="序号" width="60" align="center" />
              <template v-for="item in tableHeader" :key="item.prop">
                <px-table-column :prop="item.prop" :label="item.label">
                  <!-- 同比和环比颜色处理 -->
                  <template v-if="['yoyText', 'momText'].includes(item.prop)" #default="scope">
                    <span :class="[scope.row[item.flag] > 0 ? 'up' : 'down', scope.row[item.flag] === '-' ? 'foo' : '']">{{
                      scope.row[item.prop] ?? "-"
                    }}</span>
                  </template>
                  <template v-else #default="scope">
                    {{ scope.row[item.prop] ?? "-" }}
                  </template>
                </px-table-column>
              </template>
            </px-table>
            <px-empty v-else :image-size="50" />
          </div>
        </px-col>
      </px-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, computed, nextTick } from "vue";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import btnImageAndData from "@/views/common/energy/components/btnImageAndData/index.vue";
import { getViewConsumeLeaf } from "@/api/energy/consumeCost";
import * as echarts from "echarts";

const props = defineProps({
  queryParams: {
    type: Object,
    default: () => {}
  },
  currentNode: {
    type: String,
    default: ""
  },
  currentSystem: {
    type: String,
    default: ""
  }
});

const state = reactive({
  loading: false,
  tableHeader: [
    {
      label: "消耗能源",
      prop: "name",
      align: "left"
    },
    {
      label: "总费用（万元）",
      prop: "qty",
      align: "left",
      sortable: true
    },
    {
      label: "同比",
      prop: "yoyText",
      flag: "yoy",
      align: "left"
    },
    {
      label: "环比",
      prop: "momText",
      flag: "mom",
      align: "left"
    },
    {
      label: "折标占比",
      prop: "ratioText",
      flag: "ratio",
      align: "left"
    }
  ],
  resData: {
    summaryTable: [],
    summaryTrendStack: [],
    summaryTrend: []
  },
  tableData: []
});
const queryParams = computed(() => props.queryParams);
const currentNode = computed(() => props.currentNode);
const { loading, tableHeader, resData, tableData } = toRefs(state);
const switchType = ref("bar");
const switchText = ref("切换堆积图");
const trendChartRef = ref(null);

onMounted(() => {
  getAll();
});

const getAll = async () => {
  try {
    state.loading = true;
    const { dimension, startDate, endDate, sysId } = getParams();
    let params = {
      dimension,
      startDate,
      endDate,
      factory: "",
      sysId
    };
    if (queryParams.value.startTime && queryParams.value.endTime) {
      const res = await getViewConsumeLeaf(params);
      if (res?.summaryTable?.length) {
        let data = JSON.parse(JSON.stringify(res?.summaryTable));
        data?.forEach(i => {
          if (i.yoy !== null) {
            i.yoyText = i.yoy > 0 ? "+" + i.yoy + "%" : i.yoy + "%";
          } else {
            i.yoyText = "-";
            i.yoy = "-";
          }
          if (i.mom !== null) {
            i.momText = i.mom > 0 ? "+" + i.mom + "%" : i.mom + "%";
          } else {
            i.momText = "-";
            i.mom = "-";
          }
          if (i.ratio !== null) {
            i.ratioText = i.ratio + "%";
          } else {
            i.ratioText = "-";
            i.ratio = "-";
          }
        });
        state.tableData = data;
      } else {
        state.tableData = [];
      }
      state.resData = JSON.parse(JSON.stringify(res));
      nextTick(() => {
        res?.summaryTrend?.yaxis?.length ? drawChart(trendChartRef.value, res.summaryTrend) : "";
      });
    }
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};
let chartObj = {};

// 下载
const handlerExport = (val1, val2, val3) => {
  let name = props.currentSystem || "";
  const { dimension, startDate, endDate } = getParams();
  if (val1 === "data") {
    const params = {
      dimension,
      startDate,
      endDate,
      type: val2,
      summaryTable: state.resData.summaryTable,
      summaryTrend: state.resData.summaryTrend,
      summaryTrendStack: state.resData.summaryTrendStack
    };
    proxy.download("post", "/energy/consumeMeasure/exportConsumptionMeasurementLeaf", params, `消耗计量-${name}耗能排行.xlsx`);
  } else {
    let myChart = chartObj[val3];
    if (!myChart) return;
    // 获取Base64图片数据
    const imgUrl = myChart.getDataURL({
      type: "png",
      pixelRatio: 2,
      backgroundColor: "#fff"
    });
    // 创建并触发下载链接
    const link = document.createElement("a");
    link.href = imgUrl;
    link.download = "chart.png";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
};

// 画图
const drawChart = (dom, obj) => {
  if (dom) {
    const colors = ["#FD7C7C", "#3B82F6", "#13C2C2", "#FFC53D", "#FD7C7C", "#3B82F6", "#13C2C2", "#FFC53D"];
    let yAxisAry = [];
    let seenUnits = new Map(); // 用来进行去重
    let seriesData = [];
    obj?.yaxis?.forEach((i, idx) => {
      if (switchType.value === "stackBar") {
        seriesData.push({
          stack: "Total",
          name: i.name,
          type: "bar",
          yAxisIndex: idx,
          data: i.value,
          unit: i.unit,
          tooltip: {
            valueFormatter: function (value) {
              if (value === null || value === undefined) {
                value = "-";
              }
              return value + " " + i.unit;
            }
          }
        });
      } else {
        seriesData.push({
          name: i.name,
          type: "bar",
          yAxisIndex: idx,
          data: i.value,
          unit: i.unit,
          tooltip: {
            valueFormatter: function (value) {
              if (value === null || value === undefined) {
                value = "-";
              }
              return value + " " + i.unit;
            }
          }
        });
      }
      if (!seenUnits.has(i.unit)) {
        seenUnits.set(i.unit, true);
      }
    });
    [...seenUnits]?.forEach(([key, value], idx) => {
      yAxisAry.push({
        type: "value",
        name: key,
        alignTicks: true,
        axisLabel: {
          formatter: function (value) {
            if (value >= 1e12) {
              return (value / 1e12).toFixed(1) + "T"; // 万亿
            } else if (value >= 1e9) {
              return (value / 1e9).toFixed(1) + "B"; // 十亿
            } else if (value >= 1e6) {
              return (value / 1e6).toFixed(1) + "M"; // 百万
            } else if (value >= 1e3) {
              return (value / 1e3).toFixed(1) + "K"; // 千
            }
            return value;
          }
        },
        min: 0,
        position: idx === 0 ? "left" : "right",
        offset: idx === 0 ? 0 : (idx - 1) * 60,
        axisLine: {
          show: true,
          lineStyle: {
            color: colors[idx]
          }
        }
      });
    });
    seriesData?.forEach(i => {
      const idx = yAxisAry?.findIndex(j => j.name === i.unit);
      i.yAxisIndex = idx;
    });
    let tooltip = {
      trigger: "axis"
    };
    if (switchType.value === "stackBar") {
      tooltip.formatter = function (params) {
        let total = 0;
        // 蒸汽/热水块，只需要合计GJ类型的数据
        let paramsGj = params.filter(item => item.seriesName.includes("GJ"));
        if (paramsGj.length) {
          total = paramsGj.reduce((sum, item) => {
            item.value = item.value ? item.value : 0;
            return sum + Number(item.value);
          }, 0);
        } else {
          total = params.reduce((sum, item) => {
            item.value = item.value ? item.value : 0;
            return sum + Number(item.value);
          }, 0);
        }
        total = total.toFixed(2);
        // 生成内容
        let html = `<div>${params[0].name}</div>`;
        params.forEach(item => {
          html += `<div style="display: flex;align-items: center"><div style="width: 10px;height: 10px;background-color: ${item.color};border-radius: 50%"></div>&nbsp;<div style="flex: 1">${item.seriesName}</div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div style="font-weight: bold;">${item.value ? item.value : "-"}</div></div>`;
        });
        html += `<div style="display: flex"><span style="flex-grow: 1; margin-left: 14px">合计</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-weight: bold;float: right">${total}</span></d>`;
        return html;
      };
    }
    let options = {
      // toolbox: {
      //   show: true,
      //   feature: {
      //     saveAsImage: {
      //       title: "点击保存为图片"
      //     }
      //   }
      // },
      tooltip: tooltip,
      grid: {
        right: `${yAxisAry.length > 1 ? (yAxisAry.length - 1) * 5 : 10}%`,
        bottom: "10%"
      },
      legend: {
        type: "scroll"
      },
      xAxis: {
        type: "category",
        data: obj?.xaxis || []
      },
      yAxis: yAxisAry,
      series: seriesData
    };
    let myChart = echarts.init(dom);
    chartObj.trendChartRef = myChart;
    myChart.clear();
    myChart.setOption(options);
  }
};

// 切换
const handleSwitch = () => {
  if (switchType.value === "bar") {
    switchType.value = "stackBar";
    switchText.value = "切换柱状图";
    // 耗能趋势
    drawChart(trendChartRef.value, state.resData.summaryTrendStack);
  } else {
    switchType.value = "bar";
    switchText.value = "切换堆积图";
    // 耗能趋势
    drawChart(trendChartRef.value, state.resData.summaryTrend);
  }
};

const getParams = () => {
  let dimensionObj = {
    Hourly: "H",
    Daily: "D",
    Monthly: "M",
    Yearly: "Y"
  };
  let dimension = dimensionObj[queryParams.value.queryTimeGranularity];
  let startDate = queryParams.value.startTime;
  let endDate = queryParams.value.endTime;
  let sysId = currentNode.value || "";
  return {
    dimension,
    startDate,
    endDate,
    sysId
  };
};
</script>

<style lang="scss" scoped>
.switchTableTabs {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.top-wrap {
  display: flex;
  margin-bottom: 16px;
}

.content-wrap {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.px-row {
  flex: 1;
}

.mg-top-16 {
  margin-top: 16px;
}

.black {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 4px;

  .black-btm {
    display: flex;
    flex: 1;
    flex-direction: column;
  }

  .switch-wrap {
    position: absolute;
    top: 68px;
    right: 70px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    .text {
      font-size: 12px;
    }
  }
}

.table-wrap {
  flex: 1;
  margin-top: 16px;

  .down {
    color: #34d399;
  }

  .foo {
    color: rgb(0 0 0 / 80%);
  }

  .up {
    color: #f00;
  }
}

.chart-wrap {
  flex: 1;
  margin-top: 16px;
}

.download {
  position: absolute;
  top: 16px;
  right: 24px;
}
</style>
